﻿using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace System
{
    public static class MemberInfoExtension
    {
        /// <summary>获取程序集中标记了某标记的所有类型。</summary>
        /// <typeparam name="TAttr"></typeparam>
        /// <param name="assembly"></param>
        /// <returns></returns>
        public static IEnumerable<Type> GetTypeMarked<TAttr>(this Assembly assembly) where TAttr : Attribute
        {
            return ((IEnumerable<Type>)assembly.GetTypes()).Where(t => t.IsDefined<TAttr>());
        }

        /// <summary>找到member的指定Attribute的唯一标记实例</summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="member"></param>
        /// <returns></returns>
        public static T GetSingleAttribute<T>(this MemberInfo member) where T : Attribute
        {
            if (member == null)
                throw new ArgumentNullException(nameof(member));
            object[] customAttributes = member.GetCustomAttributes(typeof(T), false);
            if (customAttributes.Length == 1)
                return customAttributes[0] as T;
            return default(T);
        }

        /// <summary>是否标记了指定的Attribute</summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="member"></param>
        /// <returns></returns>
        public static bool IsDefined<T>(this MemberInfo member) where T : Attribute
        {
            return Attribute.IsDefined(member, typeof(T), false);
        }
    }
}